package com.axjc.gqzr.Interceptor;

import com.axjc.gqzr.common.R;
import com.axjc.gqzr.config.JwtService;
import io.swagger.v3.core.util.Json;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    JwtService jwtService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/api/v1/auth/authenticate") ) {
            return true;
        }
        String token = request.getParameter("token");
        if (token == null) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(Json.pretty(R.fail(20000, "Token无效，请重新登录")));
            return false;
        }
        boolean tokenValid1 = jwtService.validateToken(token);
        if (!tokenValid1) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(Json.pretty(R.fail(20000, "Token无效，请重新登录")));
            return false;
        }
        jwtService.SetToken(token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        ThreadLocalUtils.remove();
    }
}